#include "LoginSignUp.h"
#include "Global.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>
std::string global_username;
std::string global_digit;
Login::Login()
{
    std::ifstream f("./user.txt",std::ios::in);
    if(!f.is_open())
    {
        std::cout<<"用户文件打开失败！\n";
        exit(-1);
    }
    std::string line;
    while(getline(f,line))
    {
        std::istringstream iss(line);
        std::string user;
        std::string passwd;
        iss>>user>>passwd;
        UserList[user] = passwd;
    }
    f.close();

    // for(auto &ite :UserList)
    // {
    //     std::cout<<ite.first<<" "<<ite.second<<std::endl;
    // }
}

bool Login::login(CStrRef UserName, CStrRef Passwd)
{   
    auto ite = UserList.find(UserName);
    if(ite == UserList.end())
    {
        std::cout<<"账号不存在\n";
        return false;
    }

    if(ite->second == Passwd)
    {
        // std::cout<<"登录成功\n";
        return true;
    }
    else
    {
        std::cout<<"密码错误\n";
        return false;
    }
    
}

// void Login::RemoveUser(CStrRef UserName)
// {   
//     auto ite = UserList.find(UserName);
//     if(ite != UserList.end())
//     {
//         UserList.erase(ite);
//     }
//     Save();
// }

// void Login::ChangePasswd(CStrRef UserName, CStrRef Passwd)
// {   
//     auto ite = UserList.find(UserName);
//     if(ite != UserList.end())
//     {
//         ite->second = Passwd;
//     }
//     Save();
// }

// void Login::Save()
// {   
//     std::ofstream f("./user.txt",std::ios::out);
//     if(!f.is_open())
//     {
//         std::cout<<"打开文件失败!\n";
//         return;
//     }

//     for(auto &ite : UserList)
//     {
//         f<<ite.first<<" "<<ite.second<<std::endl;
//     }
//     f.close();
// }

void Login::show()
{   
    system("clear");
    printDecorationTop();

    printPrompt("请输入账号名:");
    std::string UserName;
    printf("~   ");
    std::cin >> UserName;
    printf("~                                          ~\n");
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");

    printPrompt("请输入密码:");
    char Passwd[40];
    printf("~   ");
    scanf("%39s", Passwd);
    printf("~                                          ~\n");
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");

    if(login(UserName, Passwd))
    {
        global_username = UserName; 
        printDecorationBottom();
        while(true)
        {
            char choice;
            std::cout << "请选择你的存档（1-3）：";
            std::cin >> choice;

            switch (choice) 
            {
                case '1':
                    std::cout << "你选择了存档 1" << std::endl;
                    global_digit = '1';
                    return;
                case '2':
                    std::cout << "你选择了存档 2" << std::endl;
                    global_digit = '2';
                    return;
                case '3':
                    std::cout << "你选择了存档 3" << std::endl;
                    global_digit = '3';
                    return;
                default:
                    std::cout << "无效的选择，请输入1到3之间的数字" << std::endl;
            }
        }
    }
    else
    {   
        sleep(1);
        system("clear");
        Scren e;
        e.show();
    }
}

void Login::printDecorationTop()
{
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
    printf("~                                          ~\n");
    printf("~   欢迎来到登录界面                       ~\n");
    printf("~                                          ~\n");
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
    printf("   /\\  /\\   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
    printf("  //\\\\//\\\\  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
    printf("  || || ||  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}

void Login::printPrompt(const char *text)
{
    printf("~                                          ~\n");
    printf("~   %-40s  ~\n", text);
    printf("~                                          ~\n");
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}

void Login::printDecorationBottom()
{
    printf("   \\\\  //   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
    printf("    \\\\//    ~ 登录成功，欢迎你！            ~\n");
    printf("     \\/     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}

void SignUp::show()
{   
    system("clear");
    printTopBorder();

    printPrompt("请输入你想要注册的账号名:");
    std::string UserName;
    std::cout << "█   ";
    std::cin >> UserName;
    std::cout << "█                                                █\n";
    std::cout << "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";

    printPrompt("请输入你想要注册的密码:");
    std::string Passwd;
    std::cout << "█   ";
    std::cin >> Passwd;
    std::cout << "█                                                █\n";
    std::cout << "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";

    printBottomBorder();
    if(CheckUserExists(UserName,"./user.txt"))
    {
        std::cout<<"该账号已经存在"<<std::endl;
    }
    else
    {
        Save(UserName,Passwd,"./user.txt");
        std::cout<<"注册成功"<<std::endl;
    }
    sleep(2);
    system("clear");
    Scren e;
    e.show();
}

void Scren::show()
{
    printTopBorder();
    printOptions();
    printBottomBorder();

    char c = 0;
    while (true) 
    {
        std::cout << "请选择 : ";
        std::cin >> c;
        // 检查输入是否有效
        if (c >= '1' && c <= '4') {
            break;
        } else {
            std::cout << "无效的选择，请重新输入。\n";
        }
    }

    //状态注册机
    faceList[c-'0']->show();
}

void Scren::printTopBorder()
{
    std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    std::cout << "~                                                    ~\n";
    std::cout << "~                    欢迎来到初始界面                ~\n";
    std::cout << "~                                                    ~\n";
    std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    std::cout << "    /\\  /\\       /\\  /\\       /\\  /\\       /\\  /\\   \n";
    std::cout << "   //\\\\//\\\\     //\\\\//\\\\     //\\\\//\\\\     //\\\\//\\\\  \n";
    std::cout << "  || || ||      || || ||      || || ||      || || ||  \n";
}

void Scren::printOptions()
{
    std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    std::cout << "~                                                    ~\n";
    std::cout << "~   🌸                1. 登录                  🌸       ~\n";
    std::cout << "~                                                    ~\n";
    std::cout << "~   🌼                2. 注册                  🌼       ~\n";
    std::cout << "~                                                    ~\n";
    std::cout << "~   🌺              3. 修改密码                🌺       ~\n";
    std::cout << "~                                                    ~\n";
    std::cout << "~   🌻              4. 注销用户                🌻       ~\n";
    std::cout << "~                                                    ~\n";
    std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
}

void Scren::printBottomBorder()
{
    std::cout << "    \\\\  //       \\\\  //       \\\\  //       \\\\  //   \n";
    std::cout << "     \\\\//         \\\\//         \\\\//         \\\\//    \n";
    std::cout << "      \\/           \\/           \\/           \\/     \n";
    std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
}

Scren::Scren()
{   
    faceList[1] = new Login;
    faceList[2] = new SignUp;
    faceList[3] = new ChangePasswd;
    faceList[4] = new RemoveUser;    
}

void SignUp::Save(const std::string &UserName, const std::string &passwd, const std::string &filePath)
{
    std::ofstream f(filePath,std::ios::app);
    if(!f.is_open())
    {
        std::cout<<"文件打开失败！保持账号密码失败！\n";
        return;
    }

    f<<UserName<<" "<<passwd<<std::endl;
    f.close();
    std::string cmd = "mkdir ./存档/" +  UserName;
    system(cmd.c_str());
    std::string cmd1 = "mkdir ./存档/" +  UserName + "/" + "1";
    system(cmd1.c_str());
    std::string cmd2 = "mkdir ./存档/" +  UserName + "/" + "2";
    system(cmd2.c_str());
    std::string cmd3 = "mkdir ./存档/" +  UserName + "/" + "3";
    system(cmd3.c_str());
}

bool SignUp::CheckUserExists(const std::string &UserName, const std::string &filePath)
{   
    std::ifstream f(filePath);
    if (!f.is_open()) 
    {
        std::cout << "文件打开失败！无法检查用户名！\n";
        return false; // 文件打开失败，假设不存在用户
    }

    std::string fileUserName, filePasswd;
    while (f >> fileUserName >> filePasswd) 
    {
        if (fileUserName == UserName) 
        {
            f.close();
            return true; // 找到匹配的用户名
        }
    }

    f.close();
    return false;
}

void SignUp::printTopBorder()
{
    std::cout << "▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄\n";
    std::cout << "█                                                █\n";
    std::cout << "█                欢迎来到注册界面                █\n";
    std::cout << "█                                                █\n";
    std::cout << "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";
    std::cout << "  /\\_/\\       /\\_/\\       /\\_/\\       /\\_/\\      \n";
    std::cout << " ( o.o )     ( o.o )     ( o.o )     ( o.o )     \n";
    std::cout << "  > ^ <       > ^ <       > ^ <       > ^ <      \n";
}

void SignUp::printPrompt(const char *text)
{
    std::cout << "█                                                █\n";
    std::cout << "█   " << text << "                              █\n";
    std::cout << "█                                                █\n";
    std::cout << "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";
}

void SignUp::printBottomBorder()
{
    std::cout << "  /\\_/\\       /\\_/\\       /\\_/\\       /\\_/\\      \n";
    std::cout << " ( o.o )     ( o.o )     ( o.o )     ( o.o )     \n";
    std::cout << "  > ^ <       > ^ <       > ^ <       > ^ <      \n";
    std::cout << "▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄\n";
}

ChangePasswd::ChangePasswd()
{
    std::ifstream f("./user.txt",std::ios::in);
    if(!f.is_open())
    {
        std::cout<<"用户文件打开失败！\n";
        exit(-1);
    }
    std::string line;
    while(getline(f,line))
    {
        std::istringstream iss(line);
        std::string user;
        std::string passwd;
        iss>>user>>passwd;
        UserList[user] = passwd;
    }
    f.close();
}

void ChangePasswd::show()
{
    system("clear");
    printTopBorder();

    printPrompt("请输入账号名:");
    std::string username;
    std::cout << "│   ";
    std::cin >> username;
    global_username = username;
    std::cout << "│                                               │\n";
    std::cout << "├───────────────────────────────────────────────┤\n";

    printPrompt("请输入旧密码:");
    std::string oldPasswd;
    std::cout << "│   ";
    std::cin >> oldPasswd;
    std::cout << "│                                               │\n";
    std::cout << "├───────────────────────────────────────────────┤\n";

    printPrompt("请输入新密码:");
    std::string newPasswd;
    std::cout << "│   ";
    std::cin >> newPasswd;
    std::cout << "│                                               │\n";
    std::cout << "├───────────────────────────────────────────────┤\n";

    // Update password logic
    if (Check(username, oldPasswd)) // Assuming login() can be used to verify old password
    {
        Changepasswd(global_username, newPasswd); // Method to change the password
        std::cout << "│  密码修改成功！                             │\n";
    }
    else
    {
        std::cout << "│                                           │\n";
    }

    std::cout << "└───────────────────────────────────────────────┘\n";
    sleep(2);
    system("clear");
    Scren e;
    e.show();
}

bool ChangePasswd::Check(CStrRef UserName, CStrRef Passwd)
{
    auto ite = UserList.find(UserName);
    if(ite == UserList.end())
    {
        std::cout<<"账号不存在\n";
        return false;
    }

    if(ite->second == Passwd)
    {
        // std::cout<<"登录成功\n";
        return true;
    }
    else
    {
        std::cout<<"密码错误\n";
        return false;
    }
}

void ChangePasswd::Changepasswd(CStrRef UserName, CStrRef Passwd)
{
    auto ite = UserList.find(UserName);
    if(ite != UserList.end())
    {
        ite->second = Passwd;
    }
    Save();
}

void ChangePasswd::Save()
{
    std::ofstream f("./user.txt",std::ios::out);
    if(!f.is_open())
    {
        std::cout<<"打开文件失败!\n";
        return;
    }

    for(auto &ite : UserList)
    {
        f<<ite.first<<" "<<ite.second<<std::endl;
    }
    f.close();
}

void ChangePasswd::printTopBorder()
{
    std::cout << "┌───────────────────────────────────────────────┐\n";
    std::cout << "│                                               │\n";
    std::cout << "│              欢迎来到修改密码界面             │\n";
    std::cout << "│                                               │\n";
    std::cout << "├───────────────────────────────────────────────┤\n";
}

void ChangePasswd::printPrompt(const std::string &text)
{
    std::cout << "│                                               │\n";
    std::cout << "│" << text << "                                  │\n";
    std::cout << "│                                               │\n";
}

void ChangePasswd::printBottomBorder()
{
    std::cout << "└───────────────────────────────────────────────┘\n";
}

RemoveUser::RemoveUser()
{
    std::ifstream f("./user.txt",std::ios::in);
    if(!f.is_open())
    {
        std::cout<<"用户文件打开失败！\n";
        exit(-1);
    }
    std::string line;
    while(getline(f,line))
    {
        std::istringstream iss(line);
        std::string user;
        std::string passwd;
        iss>>user>>passwd;
        UserList[user] = passwd;
    }
    f.close();
}

void RemoveUser::show()
{   
    system("clear");
    std::string username;  
    std::string passwd;  
    // 顶部边框和标题  
    std::cout << "=======================================" << std::endl;  
    std::cout << "|                注销用户                |" << std::endl;  
    std::cout << "=======================================" << std::endl;  

    // 提示输入用户名  
    std::cout << "| 请输入您的用户名:                       |" << std::endl;  
    std::cin >> username;  // 用户输入用户名  

    std::cout << "| 请输入您的密码:                         |" << std::endl;
    std::cin >> passwd;

    // 假设validateUser是一个验证用户名的函数  
    if (Check(username,passwd))
    {   
        deleteFile(username);
        Removeuser(username);
        // 底部边框和成功消息  
        std::cout << "=======================================" << std::endl;  
        std::cout << "| 用户 " << username << " 已成功注销。     |" << std::endl;  
        std::cout << "=======================================" << std::endl;  
    } 
    else 
    {  
        // 底部边框和失败消息  
        std::cout << "=======================================" << std::endl;  
        std::cout << "|                                      |" << std::endl;  
        std::cout << "=======================================" << std::endl;  
    }  
    sleep(2);
    system("clear");
    Scren e;
    e.show();
}

void RemoveUser::Removeuser(CStrRef UserName)
{
    auto ite = UserList.find(UserName);
    if(ite != UserList.end())
    {
        UserList.erase(ite);
    }
    Save();
}

bool RemoveUser::Check(CStrRef UserName, CStrRef Passwd)
{
    auto ite = UserList.find(UserName);
    if(ite == UserList.end())
    {
        std::cout<<"账号不存在\n";
        return false;
    }

    if(ite->second == Passwd)
    {
        // std::cout<<"登录成功\n";
        return true;
    }
    else
    {
        std::cout<<"密码错误\n";
        return false;
    }
}

void RemoveUser::Save()
{   
    std::ofstream f("./user.txt",std::ios::out);
    if(!f.is_open())
    {
        std::cout<<"打开文件失败!\n";
        return;
    }

    for(auto &ite : UserList)
    {
        f<<ite.first<<" "<<ite.second<<std::endl;
    }
    f.close();
}

void RemoveUser::deleteFile(const std::string &UserName)
{   
    // std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    // // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    // std::string filePath1 = archiveDir + "/" + UserName + "/宝箱属性.txt";
    // std::string filePath2 = archiveDir + "/" + UserName + "/怪兽属性.txt";  
    // std::string filePath3 = archiveDir + "/" + UserName + "/玩家数据.txt"; 
    // std::string filePath4 = archiveDir + "/" + UserName + "/玩家坐标.txt";

    // std::remove(filePath1.c_str());
    // std::remove(filePath2.c_str());
    // std::remove(filePath3.c_str());
    // std::remove(filePath4.c_str());

    // std::string filePath5 = archiveDir + "/" + UserName;
    // std::remove(filePath5.c_str());

    std::string archiveDir = "存档";

    std::string command = "rm -rf " + archiveDir + "/" + UserName;
    
    int result = system(command.c_str());

    if (result == 0) 
    {
    }
    else 
    {
        std::cerr << "删除目录时发生错误" << std::endl;
    }
}
